#include <sys/types.h>
#include <stdio.h>
#include <db.h>

#include "mpaxos/mpaxos.h"
#include "mpaxos/mpaxos-config.h"
#include "kvdb/kvdb.h"
#include "kvdb_log.h"

static int initilized = 0;
static DB_ENV * dbenv;
static DB * dbs[KVDB_DB_NUM];

int kvdb_init(char * dbhome) {
    if (initilized) {
        WW("kvdb already initilized");
        return 0;
    }
    int ret = db_env_create(&dbenv, 0);
    II("db_env_create: %d", ret);
    if (ret) {
        EE("db_env_create failed");
        return ret;
    }
    ret = dbenv->open(dbenv, dbhome, DB_INIT_TXN | DB_INIT_MPOOL | DB_INIT_LOCK | DB_CREATE | DB_RECOVER, 0);
    if (ret) {
        dbenv->err(dbenv, ret, "Opening enviroment: %s", dbhome);
        dbenv->close(dbenv, 0);
        return ret;
    } else {
        II("dbenv->open: %d", ret);
    }

    int i = 0;
    char tmp[5] = "?.db";
    for (i = 0; i < KVDB_DB_NUM; i++) {
        ret = db_create(&dbs[i], dbenv, 0);
        if (ret) {
            dbenv->close(dbenv, 0);
            EE("db_create failed");
            return ret;
        }
        tmp[0] = '0' + i;
        ret = dbs[i]->open(dbs[i], NULL, tmp, NULL, DB_BTREE, DB_CREATE, 0);
        if (ret) {
            dbs[i]->err(dbs[i], ret, "Opening: %s", tmp);
            dbenv->close(dbenv, 0);
            return ret;
        }
    }

    mpaxos_init();

    // register mpaxos callback
    initilized = 1;
    return KVDB_RET_OK;
}

int kvdb_destroy() {
    if (!initilized) {
        return KVDB_RET_UNINITIALISED;
    }
    mpaxos_destroy();
    return KVDB_RET_OK;
}

int kvdb_create() {
    if (!initilized) {
        return KVDB_RET_UNINITIALISED;
    }
    return KVDB_RET_OK;
}

/* vim: set et ai ts=4 sw=4: */

